<script setup>
import {ref} from 'vue'
import { showDialog } from 'vant';
import {get,post} from "../../util/request.js";
import {useRouter} from "vue-router";
import { showToast } from 'vant';


const router=useRouter()

const user=ref({})

const read=ref(false)

const sendCode = () => {
  //发送短信验证码
  get("sms/sendrcode",{phone:user.value.phone}).then(r=>{
    if(r.code==0){  // 0表示成功   1表示拜拜   2  3
      showToast('验证码已发送你手机，请查收！');
    }else {
      showToast(r.data);
    }
  })
}
const add = () => {
  //实现用户注册
  //请求接口
  post("user/register",user.value).then(r=>{
    if(r.code==0){
      router.push("/login")
    }else {
      showDialog({
        title: '注册失败！',
        message: r.data,
      })
    }
  })

}
const pass2=ref("")
const checkPass = () => {
  if(pass2.value!=user.value.password){
    showDialog({
      title: '请检查密码',
      message: '亲，两次密码不一致！！！',
    })
  }
}
</script>

<template>
  <van-nav-bar title="注册新用户" />
  <div>
    <div style="text-align: center">
      <van-image
          round
          width="10rem"
          height="10rem"
          src="https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg"
      />
    </div>
    <van-form @submit="add">
      <van-cell-group inset>
        <van-field
            v-model="user.account"
            label="账号"
            placeholder="请输入账号"
            :rules="[{ required: true, message: '请填写账号' }]"
        />
        <van-field
            v-model="user.phone"
            :rules="[{ required: true, message: '请输入手机号' }]"
            label="手机号"
            placeholder="请输入手机号"
        />
        <van-field
            v-model="user.code"
            center
            :rules="[{ required: true, message: '请输入短信验证码' }]"
            clearable
            label="短信验证码"
            placeholder="请输入短信验证码"
        >
          <template #button>
            <van-button size="small" type="primary" @click="sendCode">发送验证码</van-button>
          </template>
        </van-field>
        <!-- 输入密码 -->
        <van-field v-model="user.password"
                   :rules="[{ required: true, message: '请输入密码' }]"
                   type="password" placeholder="请输入密码" label="密码" />
        <van-field v-model="pass2" type="password"
                   :rules="[{ required: true, message: '请再次确认密码' }]"
                   label="确认密码" placeholder="请再次确认密码" @change="checkPass"/>
      </van-cell-group>
      <div style="font-size: 10px;color: grey;margin-left: 10%;margin-bottom: 20px;margin-top: 8px">
        <van-radio v-model="read" name="1">我已阅读并同意LoveCall<span class="sp">《用户协议》</span>和<span class="sp">《隐私政策》</span></van-radio>
      </div>
      <div style="margin-left: 10%;width: 80%">
        <van-button type="success" round block native-type="submit" :disabled="!read">注册账号</van-button>
      </div>
    </van-form>
  </div>
</template>

<style scoped>
.sp{
  color: blueviolet;
}
</style>
